#!/usr/bin/env bash

#### 位置自检
if [ ! $(command -v yunzai-list) ];then
echo -e "$0: 脚本位置不在PATH环境，拒绝运行"
exit 1
fi

yunzai run inss jq

data=$BASH_SANDBOX_ROOTDIR/etc/data/yunzai.install.list.json

#### 检查数据库
if [ ! -f $data ];then
echo -e "$0: 找不到数据库文件，拒绝运行"
exit 1
fi

gh_proxy=("githubfast.com" "hub.nuaa.cf")
proxy="1"

#-_-# 可能是和yunzai关系最大的插件了,以至于yunzai依赖它安装Yunzai项目和适用的Plugin

####字体颜色
##正常颜色
h01="\033[31m";   #红
h02="\033[32m";   #绿
h03="\033[36m";   #蓝
h04="\033[33m";   #黄
h07="\033[30m";   #黑
h09="\033[35m";   #紫
h10="\033[37m";   #白
h11="\033[34m";   #深蓝
##加粗混色
h13="\033[1;30m";#深灰
h14="\033[1;31m";#深红
h15="\033[1;32m";#亮绿
h16="\033[1;33m";#亮黄
h17="\033[1;34m";#深蓝
h18="\033[1;35m";#暗紫
h19="\033[1;36m";#亮蓝
h20="\033[1;37m";#浅灰
##特殊效果
h12="\033[4m";     #下划线
h06="\033[0m";     #取消效果

#### 版本信息
versions=1.9.3
times=2024/04/17

PluginName=($(jq -r '.Plugins.[] | .name' $data));
PluginAppellation=($(jq -r '.Plugins.[] | .app' $data));
PluginAddress=($(jq -r '.Plugins.[] | .url' $data));
PluginModules=($(jq -r '.Plugins.[] | .module' $data));
YunzaiName=($(jq -r '.Bots.[] | .name' $data));
YunzaiNickname=($(jq -r '.Bots.[] | .app' $data));
YunzaiAddress=($(jq -r '.Bots.[] | .url' $data));
YunzaiAuthor=($(jq -r '.Bots.[] | .author.[]' $data));
YunzaiBranch=($(jq -r '.Bots.[] | .branch' $data));

#### 管理
[ -z $1 ] && echo 'Null' && exit 127
case $1 in
-a|--all)echo ${PluginName[@]};;
-n|--all-name)echo ${PluginAppellation[@]};;
-A|--all-yunzai)echo ${YunzaiName[@]};;
-N|--all-nickname)echo ${YunzaiNickname[@]};;
-d|--dev)

mode=$2
backs=$3

case ${mode:-default} in
default)default=true;back=false;all=false;;
back)default=false;back=true;all=false;;
all)default=false;back=false;all=true;;
*)mode=default;default=true;back=false:all=false;;
esac

[ -f $BASH_SANDBOX_ROOTDIR/tmp/yunzai.get.web.log ] && rm $BASH_SANDBOX_ROOTDIR/tmp/yunzai.get.web.log

back(){
    start_curl_time=$(date +%s)
    if curl -sL --connect-timeout 10 https://${URL} 1> $BASH_SANDBOX_ROOTDIR/tmp/yunzai.get.web.log;then
      old_good=$good
      let good++
      new_good=$good
    else
      old_bad=$bad
      let bad++
      new_bad=$bad
      bad_url=(${bad_url[@]} ${PluginName[$i]})
    fi    
    end_curl_time=$(date +%s)
    curl_times=$((end_curl_time - start_curl_time))
    curl_log_size=$(du -sb $BASH_SANDBOX_ROOTDIR/opt/yunzai.get.web.log | awk '{print $1}')
    if [[ $curl_log_size == 0 ]]||[[ $curl_times == 0 ]];then
      curl_get_speed_kbit=0
    else
      curl_get_speed_bit=$((curl_log_size / curl_times))
      curl_get_speed_kbit=$(awk "BEGIN{print $curl_get_speed_bit / 1024}")
    fi
    percentage=$((i * 100 / total_steps))
    end_time=$(date +%s)
    main_time=$((end_time - start_time))
    hours=$((main_time / 3600))
    minutes=$((main_time % 3600 / 60))
    seconds=$((main_time % 3600 % 60))    
    times=$(printf "%02d:%02d:%02d" $hours $minutes $seconds)
    eta_time=$((total_steps * curl_times - i * curl_times))
    eta_hours=$((eta_time / 3600))
    eta_minutes=$((eta_time % 3600 / 60))
    eta_seconds=$((eta_time % 3600 % 60))
    eta_times=$(printf "%02d:%02d:%02d" $eta_hours $eta_minutes $eta_seconds)
      ${all:-false}&&(
      [[ $1 == Plugin ]]&&back=$(( 66 - 19 - ${#PluginAddress[$i]}))
      [[ $1 == Yunzai ]]&&back=$(( 66 - 19 - ${#YunzaiAddress[$i]}))
      [[ $1 == Plugin ]]&&echo -en "[*] https://${PluginAddress[$i]} 结果: "
      [[ $1 == Yunzai ]]&&echo -en "[*] https://${YunzaiAddress[$i]} 结果: "
      if [[ $old_good < $new_good  ]];then
        echo -ne "可用"
      else
        echo -ne "异常"
      fi
      printf "%*s\n" $back)
      ${backs:-false}||bar_length=40
      echo -en "[$(printf '%*s' $((percentage * bar_length / 100)) | tr ' ' '#')$(printf '%*s' $(($bar_length - $((percentage * bar_length / 100)))))] $percentage% "
      ${backs:-false}&&echo -en "$total_steps/$i $times $(printf %.2f $curl_get_speed_kbit)KB/s ETA[$eta_times]   \r"||echo -en "\r"
      let current_step++
}

default(){
  if [[ $1 == Plugin ]];then
    echo -en "[*] https://${PluginAddress[$i]} 结果: "
    if curl -sL  https://${URL} 1> $BASH_SANDBOX_ROOTDIR/opt/yunzai.get.web.log;then
      echo "可用"
      let good++
    else
      echo "异常"
      let bad++
      bad_url=(${bad_url[@]} ${PluginName[$i]})
    fi
  elif [ $1 == Yunzai ];then
    echo -en "[*] https://${YunzaiAddress[$i]} 结果: "
    if curl -sL  https://${URL} 1> $BASH_SANDBOX_ROOTDIR/opt/yunzai.get.web.log;then
      echo "可用"
      let good++
    else
      echo "异常"
      let bad++
      bad_url=(${bad_url[@]} ${YunzaiName[$i]})
    fi
  fi
}

echo "测试仓库地址可用性..."

good=0
bad=0
mode=tcher
start_time=$(date +%s)
current_step=0
bar_length=20
bad_url=()

if [[ ${4:-Plugin} == Plugin ]];then

echo -e "共计 ${#PluginAddress[@]} 个仓库待检查"

total_steps=${#PluginAddress[@]}

  for ((i=0;i<${#PluginAddress[@]};i++));do
    [[ ${PluginAddress[$i]} =~ ^github.* ]] &&
      URL=$(sed "s/github.com/${gh_proxy[${proxy:-1}]}/" <<< ${YunzaiAddress[$i]}) ||
    URL=${PluginAddress[$i]}
    ${default:-true}&&default Plugin
    ${back:-false}&&back Plugin
    ${all:-false}&&back Plugin
  done

if [[ ! ${#bad_url[@]} = 0 ]];then
  echo -e "\n以下可能是失效或无法访问的项目:"
  for i in ${bad_url[@]};do
    sleep 0.01
    echo $i
  done
fi

echo -e "\n完成。\n检索了 ${#PluginAddress[@]} 个地址，$good 个有效地址，有 $bad 个地址无法访问"

elif [[ ${4:-Plugin} == Yunzai ]];then

#过滤彩蛋
YunzaiAddresss=()
for ((i=0;i<${#YunzaiAddress[@]};i++));do
  ! [[ ${YunzaiAddress[$i]} == "这是彩蛋啦^_^" ]] &&
  YunzaiAddresss=(${YunzaiAddresss[@]} ${YunzaiAddress[$i]})
done
YunzaiAddress=(${YunzaiAddresss[@]})

echo -e "共计 ${#YunzaiAddress[@]} 个仓库待检查"

total_steps=${#YunzaiAddress[@]}

  for ((i=0;i<${#YunzaiAddress[@]};i++));do
    [[ ${YunzaiAddress[$i]} =~ ^github.* ]] &&
    URL=$(sed "s/github.com/${gh_proxy[${proxy:-1}]}/" <<< ${YunzaiAddress[$i]}) ||
    URL=${YunzaiAddress[$i]}
    ${default:-true}&&default Yunzai
    ${back:-false}&&back Yunzai
    ${all:-false}&&back Yunzai
  done

if [[ ! ${#bad_url[@]} = 0 ]];then
  echo -e "\n以下可能是失效或无法访问的项目:"
  for i in ${bad_url[@]};do
    sleep 0.01
    echo $i
  done
fi

echo -e "\n完成。\n检索了 ${#YunzaiAddress[@]} 个地址，$good 个有效地址，有 $bad 个地址无法访问"
fi
;;
-m|--markdown)
[ -z $(command -v lynx) ]&&yunzai run inss lynx&&echo "CHARACTER_SET:utf-8" >> /etc/lynx.cfg
if [ ! -z $1 ];then
echo -e \
"按[${h02}Q${h06}]键离开界面 按[${h02}↑${h06}][${h02}↓${h06}]键/鼠标滚轮/触屏上下滑动翻阅"
echo -e "$h16## Markdown在线文档 ##$h06"
url=($(yunzai-list $2))
if [[ ${url[0]} =~ ^gitee.* ]];then
echo -e "$h19此为 Gitee 项目$h06"
lynx -dump https://${url[0]} | sed '/Loading.../,$!d;/我们将于2个工作日内通过站内信反馈结果给你/,$d' | head -n -10 | sed '1,3d' | sed 's/\[\([0-9]\{1,3\}\)\]//g'
elif [[ ${url[0]} =~ ^github.* ]];then
echo -e "$h19此为 Github 项目，尝试转接到$h12 ${gh_proxy[${proxy:-0}]} $h06$h19镜像$h06"
lynx -dump https://$(echo ${url[0]}  | sed "s/^github.com/${gh_proxy[${proxy:-0}]}/") | sed '/^\[.*\]README.md/,$!d;/^About/,$d;s/githubfast/github/' | sed '1,2d' | sed 's/\[\([0-9]\{1,3\}\)\]//g' || echo Error
fi
fi | less -Rm;;
-M|--MarkDown)
[ -z $(command -v lynx) ]&&yunzai run inss lynx&&echo "CHARACTER_SET:utf-8" >> /etc/lynx.cfg
if [ ! -z $1 ];then
echo -e \
"按[${h02}Q${h06}]键离开界面 按[${h02}↑${h06}][${h02}↓${h06}]键/鼠标滚轮/触屏上下滑动翻阅"
echo -e "$h16## Markdown在线文档 ##$h06"
url=($(yunzai-list --search-yunzai $2))
if [[ ${url[0]} =~ ^gitee.* ]];then
echo -e "$h19此为 Gitee 项目$h06"
lynx -dump https://${url[0]} | sed '/Loading.../,$!d;/我们将于2个工作日内通过站内信反馈结果给你/,$d' | head -n -10 | sed '1,3d' | sed 's/\[\([0-9]\{1,3\}\)\]//g'
elif [[ ${url[0]} =~ ^github.* ]];then
echo -e "$h19此为 Github 项目，尝试转接到$h12 ${gh_proxy[${proxy:-0}]} $h06$h19镜像$h06"
lynx -dump https://$(echo ${url[0]} |  sed "s/^github.com/${gh_proxy[${proxy:-0}]}/") | sed '/^\[.*\]README.md/,$!d;/^About/,$d;s/githubfast/github/' | sed '1,2d' | sed 's/\[\([0-9]\{1,3\}\)\]//g' || echo Error
fi
fi | less -Rm;;
-v|--version)echo $versions $time ${#PluginName[@]};;
-h|-help)echo -e \
"用法：yunzai-list [选项] ...\n"\
" <Name>                      查询Plugin\n"\
" -a --all                    展示所有可查询的Plugin\n"\
" -n --all-name               展示所有Plugin名称\n"\
" -m --markdown <Name>        Plugin项目自述\n"\
" -S --search-yunzai          查询Yunzai项目\n"\
" -A --all-yunzai             展示所有可查询的Yunzai项目\n"\
" -N --all-nickname           展示所有Yunzai名称\n"\
" -M --MarkDown <Name>        Yunzai项目自述\n"\
" -d --dev                    检查仓库[实验性的,非常耗时的]\n"\
" -h --help                   显示此帮助\n"\
" -v --version                显示版本\n";;

-S|--search-yunzai)
#忽略大小写匹配
shopt -s nocasematch
YunzaiItem=()
YunzaiSequence=()
for i in "${!YunzaiName[@]}"; do
  if [[ ${YunzaiName[$i]} =~ ^$2 ]]; then
    YunzaiItem+=(${YunzaiName[$i]})
    YunzaiSequence+=($i)
  fi
done
#过滤
YunzaiSequence=${YunzaiSequence[0]}
if [[ ${#YunzaiItem[@]} = 0 ]];then
  echo Null
elif [[ ${#YunzaiItem[@]} > 1 ]];then
  echo Null
elif [[ ${#YunzaiItem[@]} = 1 ]] ;then
  if [[ ! ${YunzaiAddress[$YunzaiSequence]} == "%EasterEgg" ]];then
    echo ${YunzaiAddress[YunzaiSequence]} ${YunzaiItem[0]} ${YunzaiAuthor[YunzaiSequence]} ${YunzaiNickname[YunzaiSequence]} ${YunzaiBranch[YunzaiSequence]}
  else
    echo "这是彩蛋啦^_^"
  fi
fi;;

*)
#忽略大小写匹配
shopt -s nocasematch
PluginItem=()
PluginSequence=()
for i in "${!PluginName[@]}"; do
  if [[ ${PluginName[$i]} =~ ^$1 ]]; then
    PluginItem+=(${PluginName[$i]})
    PluginSequence+=($i)
  fi
done
#过滤
PluginSequence=${PluginSequence[0]}
if [[ ${#PluginItem[@]} = 0 ]];then
  echo Null
elif [[ ${#PluginItem[@]} > 1 ]];then
  echo Null
elif [[ ${#PluginItem[@]} = 1 ]] ;then
  echo ${PluginAddress[$PluginSequence]} ${PluginItem[0]} ${PluginModules[$PluginSequence]} ${PluginAppellation[$PluginSequence]}
fi
esac
